package com.lanhao.aot.nettyudp;

import java.net.InetSocketAddress;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.socket.DatagramPacket;

/**
 * 服务端业务处理
 */
public class UdpServerHandler extends SimpleChannelInboundHandler<DatagramPacket> {
	private static final Logger LOG = LoggerFactory.getLogger(UdpServerHandler.class);

	@Override
	protected void channelRead0(ChannelHandlerContext ctx, DatagramPacket msg) throws Exception {
		ByteBuf buf = msg.copy().content();
		byte[] req = new byte[buf.readableBytes()];
		buf.readBytes(req);
		String body = new String(req, "UTF-8");
		InetSocketAddress remoteAddress = msg.sender();
		String clientIp = remoteAddress.getAddress().getHostAddress();
		LOG.info("收到客户端{}的连接信息{}", clientIp, body);// 打印收到的信息
		if(body.startsWith("AntGatewaySearch:")) {
			// 向客户端发送消息
			String mac = "AABBCCDDEEFF";
			// 由于数据报的数据是以字符数组传的形式存储的，所以传转数据
			byte[] bytes = mac.getBytes("UTF-8");
			DatagramPacket data = new DatagramPacket(Unpooled.copiedBuffer(bytes), msg.sender());
			// 向客户端发送消息
			ctx.writeAndFlush(data);
		}
	}
}
